package br.edu.ufcg.lsd.wbis.control.util;

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import br.edu.ufcg.lsd.wbis.control.exception.UnexpectedException;

/**
 * This class provides methods for supporting the security issues taken into
 * account by the system.
 * 
 * @author Renato Miceli
 */
public class SecurityUtil {

	/**
	 * Generates an SHA-1 hash of the input string.
	 * 
	 * @param value
	 *            the string to be hashed
	 * @return an SHA-1 hash of the input string
	 */
	public static String generateHash(String value) {
		MessageDigest digest;
		try {
			digest = MessageDigest.getInstance("SHA-1");
		} catch (NoSuchAlgorithmException e) {
			throw new UnexpectedException("Unknown hashing algorithm.", e);
		}
		Charset charset = Charset.forName("ISO-8859-1");
		byte[] hashInBytes = digest.digest(value.getBytes(charset));

		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < hashInBytes.length; i++) {
			int halfByte = (hashInBytes[i] >>> 4) & 0x0F;
			int twoHalfs = 0;
			do {
				if ((0 <= halfByte) && (halfByte <= 9)) {
					buf.append((char) ('0' + halfByte));
				} else {
					buf.append((char) ('a' + (halfByte - 10)));
				}
				halfByte = hashInBytes[i] & 0x0F;
			} while (twoHalfs++ < 1);
		}

		return buf.toString();
	}
}
